package com.ali.music.multiimageselector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.widget.Toast;

import com.ali.music.multi_image_selector.R;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import me.nereo.multi_image_selector.MultiContent;
import me.nereo.multi_image_selector.MultiImagePreviewActivity;
import me.nereo.multi_image_selector.MultiImagePreviewFragment;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import me.nereo.multi_image_selector.MultiImageSelectorFragment;
import me.nereo.multi_image_selector.PrivateContent;
import me.nereo.multi_image_selector.utils.FileUtils;

/**
 * 在此写用途
 *
 * @version V1.0 <描述当前版本功能>
 * @FileName: com.ali.music.multiimageselector.MultiImageSelectorUtils.java
 * @author: zhiwei
 * @date: 2016-01-14 16:06
 */
public class MultiImageSelectorUtils {

    /***
     * 裁剪图片
     *
     * @param activity    {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @param uri         图片的Uri
     * @param requestCode the code
     */
    public static void cropPicture(Object activity, Uri uri, int requestCode) {
        checkeObject(activity);

        Intent innerIntent = new Intent("com.android.camera.action.CROP");
        innerIntent.setDataAndType(uri, "image/*");
        innerIntent.putExtra("crop", "true");// 才能出剪辑的小方框，不然没有剪辑功能，只能选取图片
        innerIntent.putExtra("aspectX", 1); // 放大缩小比例的X
        innerIntent.putExtra("aspectY", 1);// 放大缩小比例的X   这里的比例为：   1:1
        innerIntent.putExtra("outputX", 320);  //这个是限制输出图片大小
        innerIntent.putExtra("outputY", 320);
        innerIntent.putExtra("return-data", true);
        innerIntent.putExtra("scale", true);
        startActivityForResult(activity, innerIntent, requestCode);
    }

    /**
     * 调用系统相机拍照，并保存图片到系统相册.若系统相册路径获取失败，则保存到app的cach目录
     *
     * @param object {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @return File or null, file is the picture will sava path
     */
    public static File tackPicture(Object object) {
        Context context = checkeObject(object);
        File mTemoTackPicture = FileUtils.getDicmOrCach(context);
        return tackPicture(object, mTemoTackPicture);
    }

    /**
     * 调用系统相机拍照，图片保存到指定目录
     *
     * @param savePath 图片保存到指定目录
     * @param object   {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @return File or null, file is the picture will sava path
     */
    public static File tackPicture(Object object, File savePath) {
        Context context = checkeObject(object);
        if (savePath.exists()) {
            throw new IllegalArgumentException(" the save path is exists, path=" + savePath);
        }
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断系统相机是否可用
        if (cameraIntent.resolveActivity(context.getPackageManager()) != null) {
            // 设置系统相机拍照后的输出路径
            // 创建临时文件
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(savePath));
        } else {
            Toast.makeText(context, R.string.multi_msg_no_camera, Toast.LENGTH_SHORT).show();
            return null;
        }
        startActivityForResult(object, cameraIntent, MultiContent.REQUEST_CAMERA);
        return savePath;
    }

    private static Context checkeObject(Object object) {
        if (!(object instanceof Fragment || object instanceof Activity || object instanceof android.app.Fragment)) {
            throw new IllegalArgumentException(" args mast Activity or Fragment");
        }
        Context context = null;
        if (object instanceof Activity) {
            context = (Activity) object;
        } else if (object instanceof Fragment) {
            Fragment fragment = (Fragment) object;
            context = fragment.getActivity();
        } else if (object instanceof android.app.Fragment) {
            android.app.Fragment fragment = (android.app.Fragment) object;
            context = fragment.getActivity();
        }
        return context;
    }

    private static void startActivityForResult(Object object, Intent intent, int requestCode) {
        if (object instanceof Activity) {
            Activity activity = (Activity) object;
            activity.startActivityForResult(intent, requestCode);
        } else if (object instanceof Fragment) {
            Fragment fragment = (Fragment) object;
            fragment.startActivityForResult(intent, requestCode);
        } else if (object instanceof android.app.Fragment) {
            android.app.Fragment fragment = (android.app.Fragment) object;
            fragment.startActivityForResult(intent, requestCode);
        }
    }

    /**
     * 启动图片预览。可预览preViewList数组中的图片。
     * 有三种模式：
     * 1、预览图片。提供放大缩小功能。退出是不返回任何值。
     * 2、提供图片选择功能，点击完成后，返回选中的图片。
     * 3、预览，并下载转存图片。
     *
     * @param object       {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @param preViewList  预览列表.实际能看到的图片列表
     * @param selectedList 已选择选择列表，preViewList中已经选中的列表
     * @param maxNum       最大可选择图片总数
     * @param position     当前要显示的图片在列表中的位置。若大于列表size 或小于0，则显示第一张图片
     * @param canSave      是否可以保存，true，表示需要现实保存按钮，
     * @param savePath     保存网络图片路径。保存当前图片到 savePath参数的路径；若为空，则存储到相机相册。
     */
    private static void previewPictures(Object object, Collection<String> preViewList,
                                        Collection<String> selectedList, int maxNum, int position, boolean canSave, String savePath, int mode) {
        checkeObject(object);
        ArrayList<String> preViewArray = tranform(preViewList);
        ArrayList<String> selectArray = tranform(selectedList);

        Bundle bundle = new Bundle();
        bundle.putStringArrayList(PrivateContent.EXTRA_PREVIEW_SELECTED_LIST, preViewArray);
        bundle.putStringArrayList(PrivateContent.EXTRA_DEFAULT_SELECTED_LIST, selectArray);
        bundle.putInt(PrivateContent.EXTRA_SELECT_COUNT, maxNum);
        bundle.putInt(PrivateContent.EXTRA_SELECTED_POSITION, position);
        bundle.putBoolean(PrivateContent.EXTRA_CAN_SAVE, canSave);
        bundle.putString(PrivateContent.EXTRA_SAVE_PATH, savePath);
        bundle.putInt(PrivateContent.EXTRA_MODE, mode);
        if (object instanceof Activity) {
            Activity activity = (Activity) object;
            Intent intent = new Intent(activity, MultiImagePreviewActivity.class);
            intent.putExtra(PrivateContent.BUNDLE_KEY, bundle);
            if (mode == MultiImagePreviewFragment.MODE_PREVIEW) {
                activity.startActivity(intent);
            } else {
                activity.startActivityForResult(intent, MultiContent.REQUEST_PREVIEW_CODE);
            }
        } else if (object instanceof Fragment) {
            Fragment fragment = (Fragment) object;
            Intent intent = new Intent(fragment.getActivity(), MultiImagePreviewActivity.class);
            intent.putExtra(PrivateContent.BUNDLE_KEY, bundle);
            if (mode == MultiImagePreviewFragment.MODE_PREVIEW) {
                fragment.startActivity(intent);
            } else {
                fragment.startActivityForResult(intent, MultiContent.REQUEST_PREVIEW_CODE);
            }
        } else if (object instanceof android.app.Fragment) {
            android.app.Fragment fragment = (android.app.Fragment) object;
            Intent intent = new Intent(fragment.getActivity(), MultiImagePreviewActivity.class);
            intent.putExtra(PrivateContent.BUNDLE_KEY, bundle);
            if (mode == MultiImagePreviewFragment.MODE_PREVIEW) {
                fragment.startActivity(intent);
            } else {
                fragment.startActivityForResult(intent, MultiContent.REQUEST_PREVIEW_CODE);
            }
        }

    }

    /**
     * 更新系统相册
     *
     * @param context   Context
     * @param imageFile the image path
     */
    public static void updateMedia(Context context, File imageFile) {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile)));
        // 刷新系统相册
    }

    /**
     * 预览模式。只提供预览功能
     *
     * @param object      {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @param preViewList 预览列表.实际能看到的图片列表
     * @param position    当前要显示的图片在列表中的位置。若大于列表size 或小于0，则显示第一张图片
     */
    public static void previewPictures(Object object, ArrayList<String> preViewList, int position) {
        previewPictures(object, preViewList, null, 0, position, false, null, MultiImagePreviewFragment.MODE_PREVIEW);
    }

    private static ArrayList<String> tranform(Collection<String> collection) {
        ArrayList<String> stringArrayList = new ArrayList<>();
        if (collection != null && collection.size() > 0) {
            for (String url : collection) {
                stringArrayList.add(url);
            }
        }
        return stringArrayList;
    }

    /**
     * 图片预览、选择模式。
     * 可预览，并选择图片功能，选中图片通过{@link Activity#onActivityResult(int, int, Intent)}方式返回。
     * <p>
     * 注意：调用的Activity需实现{@link Activity#onActivityResult(int, int, Intent)}方法。
     * 返回的requestCode值为{@link MultiContent#REQUEST_PREVIEW_CODE}
     * 通过
     *
     * @param object       {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @param preViewList  预览图片url列表.实际能看到的图片列表
     * @param selectedList 已选择选择列表，preViewList中已经选中的列表
     * @param maxNum       最大可选择图片总数
     * @param position     当前要显示的图片在列表中的位置。若大于列表size 或小于0，则显示第一张图片
     */
    public static void previewAndChoose(Object object, ArrayList<String> preViewList,
                                        ArrayList<String> selectedList, int maxNum, int position) {
        previewPictures(object, preViewList, selectedList, maxNum, position, false, null, MultiImagePreviewFragment.MODE_CHOOSE);
    }

    /**
     * 图片预览、存储功能.
     * 预览图片列表，并存储图片到指定位置，若savePath为null或空，则存储到相机相册。
     *
     * @param object      {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @param preViewList 预览列表.实际能看到的图片列表
     * @param position    当前要显示的图片在列表中的位置。若大于列表size 或小于0，则显示第一张图片
     * @param savePath    保存网络图片路径。保存当前图片到 savePath参数的路径下；若为空，则存储到相机相册。
     *                    <p>
     *                    返回List<String>.为存储的地址
     */
    public static void previewAndSave(Object object, ArrayList<String> preViewList,
                                      int position, String savePath) {
        previewPictures(object, preViewList, null, 0, position, true, savePath, MultiImagePreviewFragment.MODE_SAVE);
    }


    /**
     * 图片选择
     *
     * @param object    {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @param mode      选择模式。参看：{@link MultiImageSelectorFragment#MODE_SINGLE} {@link MultiImageSelectorFragment#MODE_SINGLE_CROP} {@link MultiImageSelectorFragment#MODE_MULTI}
     * @param isCamera  true 现实拍照按钮，点击调系统相机,false不现实相机按钮。
     * @param maxCount  最多选择个数
     * @param selecteds 已选择的列表。若图片中
     */
    private static final void selectorPicture(Object object, int mode, boolean isCamera, int maxCount,
                                              ArrayList<String> selecteds) {
        checkeObject(object);

        Bundle bundle = new Bundle();
        bundle.putInt(PrivateContent.EXTRA_MODE, mode);
        bundle.putBoolean(PrivateContent.EXTRA_SHOW_CAMERA, isCamera);
        bundle.putInt(PrivateContent.EXTRA_SELECT_COUNT, maxCount);
        bundle.putStringArrayList(PrivateContent.EXTRA_DEFAULT_SELECTED_LIST, selecteds);

        if (object instanceof Activity) {
            Activity activity = (Activity) object;
            Intent intent = new Intent(activity, MultiImageSelectorActivity.class);
            intent.putExtra(PrivateContent.BUNDLE_KEY, bundle);
            activity.startActivityForResult(intent, MultiContent.REQUESTF_SELECTOR_CODE);
        } else if (object instanceof Fragment) {
            Fragment fragment = (Fragment) object;
            Intent intent = new Intent(fragment.getActivity(), MultiImageSelectorActivity.class);
            intent.putExtra(PrivateContent.BUNDLE_KEY, bundle);
            fragment.startActivityForResult(intent, MultiContent.REQUESTF_SELECTOR_CODE);
        } else if (object instanceof android.app.Fragment) {
            android.app.Fragment fragment = (android.app.Fragment) object;
            Intent intent = new Intent(fragment.getActivity(), MultiImageSelectorActivity.class);
            intent.putExtra(PrivateContent.BUNDLE_KEY, bundle);
            fragment.startActivityForResult(intent, MultiContent.REQUESTF_SELECTOR_CODE);
        }
    }

    /**
     * 多图选择，最多允许选择maxCount张图片
     *
     * @param object   {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @param isCamera true 现实拍照按钮，点击调系统相机,false不现实相机按钮。
     * @param maxCount 最多选择个数
     */
    public static final void selectorMulti(Object object, boolean isCamera, int maxCount) {
        selectorPicture(object, MultiImageSelectorFragment.MODE_MULTI, isCamera, maxCount, null);
    }

    /**
     * 选择单张图片
     *
     * @param object   {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @param isCamera true 现实拍照按钮，点击调系统相机,false不现实相机按钮。
     */
    public static final void selectorSingle(Object object, boolean isCamera) {
        selectorPicture(object, MultiImageSelectorFragment.MODE_SINGLE, isCamera, 0, null);
    }

    /**
     * 选择单张图片，并对图片进行裁剪
     *
     * @param object   {@link Activity} 或者 {@link Fragment} {@link android.app.Fragment}, 否则抛出{@link IllegalArgumentException}
     * @param isCamera true 现实拍照按钮，点击调系统相机,false不现实相机按钮。
     */
    public static final void selectorCrop(Object object, boolean isCamera) {
        selectorPicture(object, MultiImageSelectorFragment.MODE_SINGLE_CROP, isCamera, 0, null);
    }
}
